package com.t216.dm216.controller;

import com.t216.dm216.common.*;
import com.t216.dm216.pojo.DmUser;
import com.t216.dm216.pojo.dto.DmUserDTO;
import com.t216.dm216.pojo.dto.Token;
import com.t216.dm216.service.DmUserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user/api/p")
public class DmUserController {
    @Resource
    private DmUserService dmUserService;

    @Resource
    private RedisUtil redisUtil;


    @PostMapping("/login")
    public Result login(@RequestBody DmUser user){
        DmUser userInfo = dmUserService.getUserByPhone(user.getPhone());
        if(userInfo == null){
            return Result.error("1006","账号有误,登录失败");
        }else{
            //严格来讲 下面这段代码不能出现在controller层
            if (userInfo.getPassword().equals(MD5Util.md5(user.getPassword()))){
                //登录成功
                DmUserDTO loginUser = dmUserService.getUserById(userInfo.getId());
                Token token = TokenUtil.getToken();
                Object[]objects = {loginUser,token};
                redisUtil.setExpire(token.getToken(),loginUser, Constant.EXP_SECOND);
                return Result.success(objects);
            }else{
                return Result.error("1006","密码有误,登录失败");
            }
        }

    }
}
